package stmo.栈;

import java.util.Iterator;

/**
 *   栈
 */


public class Stack<T> implements Iterable<T>{

    private Node head;

    private int N;

    private class Node {

        private T item;

        private Node next;

        public Node(T item,Node next) {
            this.item = item;
            this.next = next;
        }
    }

    //构造方法
    public Stack() {
        this.head = new Node(null,null);
        this.N = 0;
    }

    //判断当前栈中元素个数是否为空
    public boolean isEmpty() {
        return N == 0;
    }

    //获取栈中元素的个数
    public int size() {
        return N;
    }

    //把元素压入栈中
    public void push(T t) {
        Node addNode = new Node(t,head.next);
        head.next = addNode;
        N++;
    }

    //弹出栈顶元素
    public T pop() {
        Node n = head.next;
        if (n == null) {
            return null;
        }
        head.next = head.next.next;
        N--;
        return n.item;
    }


    /**
     *  遍历
     */
    @Override
    public Iterator iterator() {
        return new SIterator();
    }

    private class SIterator implements Iterator{

        private Node n;

        public SIterator() {
            this.n = head;
        }

        @Override
        public boolean hasNext() {
            return n.next != null;
        }

        @Override
        public Object next() {
            n = n.next;
            return n.item;
        }
    }

}
